/**
 * @description 首页 api 路由
 * @author chengpeng
 */

const router = require('koa-router')()
const {
    loginCheck
} = require('../../middlewares/loginCheckes')
const {
    create,
    getHomeList
} = require('../../controller/blog-home')
const blogValidate = require('../../validator/blog')
const {
    genValidator
} = require('../../middlewares/validator')
const {
    getBlogListStr
} = require('../../utils/blog')

router.prefix('/api/blog')

// 创建微博
router.post('/create', loginCheck, genValidator(blogValidate), async (ctx, next) => {
    const {
        content,
        image
    } = ctx.request.body
    const {
        id: userId
    } = ctx.session.userInfo

    ctx.body = await create({
        userId,
        content,
        image
    })
})

// 加载更多
router.get('/loadMore/:pageIndex', loginCheck, async (ctx, next) => {
    let {
        pageIndex
    } = ctx.params
    pageIndex = parseInt(pageIndex)
    const {
        id: userId
    } = ctx.session.userInfo

    const result = await getHomeList(userId, pageIndex)
    // 渲染为html字符串
    result.data.blogListTpl = getBlogListStr(result.data.blogList)
    ctx.body = result
})


module.exports = router